import featureAbility from '@ohos.ability.featureAbility'
import relationalStore from '@ohos.data.relationalStore';
import ArrayList from '@ohos.util.ArrayList';
import AdvertDao from "./AdvertDao"
const STORE_CONFIG = {
  name: "AppDatebase.db",
  securityLevel: relationalStore.SecurityLevel.S1
};
const TAG ="DbHelper:"
const  TABLES_SQL= [
  "CREATE TABLE IF NOT EXISTS `advert` (`id` INTEGER NOT NULL, `title` TEXT NOT NULL, `img` TEXT NOT NULL, `url` INTEGER NOT NULL, `expireTime` INTEGER NOT NULL, `base64Str` TEXT NOT NULL, " +
    " PRIMARY KEY(`id`))"]

 class DbHelper{
  private dbStore :relationalStore.RdbStore;
  private advertDao = new AdvertDao()
  getDb(context){
    let promise = relationalStore.getRdbStore(context, STORE_CONFIG);
    promise.then(async (rdbStore) => {
      this.dbStore= rdbStore;
      this.createAllTables(this.dbStore)
      console.info(`Get RdbStore successfully.`);
    }).catch((err) => {
      console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`);
    })
  }
  insert (tableName,valuesBucket){

    return this.dbStore.insert(tableName,valuesBucket)
  }
   delete(predicates:relationalStore.RdbPredicates):Promise<number>{
     return this.dbStore.delete(predicates)
   }
  query<T>(predicates:relationalStore.RdbPredicates,columns?:Array<string>){
    return new Promise<ArrayList<T>>((resolve, reject)=>{
      console.info(TAG+"query Start ")
      var list =new ArrayList<T>()
      this.dbStore.query(predicates,columns).then(resultSet=>{
        console.info(TAG+"query result ")
        console.info(TAG+"query rowCount  length " +resultSet.rowCount +"columnCount"  +resultSet.columnCount)
         while (resultSet.goToNextRow()){
           var obj = {  };
           for (let i = 0; i < resultSet.columnCount ; i++) {
             console.info(TAG+"query getColumnName" + resultSet.getColumnName(i) + resultSet.getString(i))
             obj[resultSet.getColumnName(i)]=resultSet.getString(i)

           }
           list.add(<T>obj)

         }
        resolve(list)
        console.info(TAG+"query end ")
      }).catch(error =>{
        reject(error)
        console.info(TAG+"queryerror "+error.message)
      })
    })
  }

   update(valuesBucket,predicates:relationalStore.RdbPredicates,columns?:Array<string>){
     return this.dbStore.update(valuesBucket,predicates)
   }

  getAdvertDao(){

    return  this.advertDao
  }
  createAllTables(rdb :relationalStore.RdbStore){
    TABLES_SQL.forEach(sql =>{
      rdb.executeSql(sql).then(()=>{
        console.info("创建表成功:"+sql)
      }).catch(error =>{
        console.info("创建表失败")
      })
    })

  }

}
const dbHelper =new DbHelper();
export  default dbHelper